package phylacterium.servlets;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.catalina.Session;

import phylacterium.beans.AccountBean;
import phylacterium.beans.MapBean;
import phylacterium.beans.RegisterBean;
import phylacterium.entities.LoginEntity;
import phylacterium.entities.UserEntity;
import phylacterium.tools.DBException;
import phylacterium.tools.DBOperations;

/**
 * Servlet implementation class AccountServlet
 */
public class AccountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private AccountBean bean;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AccountServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			ArrayList<String[]> genres = DBOperations
					.select("SELECT id,name FROM Genres ORDER BY 2 ASC");
			ArrayList<String[]> education = DBOperations
					.select("SELECT id,name FROM Education");
			
			if (request.getSession() == null || request.getSession().getAttribute("userId") == null){
				throw new DBException(11, "Session seams to be invalid");
			}
			
			UserEntity accountInfo = DBOperations.getAccountInfo((Integer)request.getSession().getAttribute("userId"));
					
			if (bean == null){
				bean = new AccountBean(genres, education);
				bean.user = accountInfo;
			}
			else {
				bean.genres = genres;
				bean.education = education;
			}
			
			request.setAttribute("bean", bean);

			bean = null;

			ServletContext ctx = this.getServletContext();
			RequestDispatcher dispatcher = ctx
					.getRequestDispatcher("/account.jsp");

			dispatcher.forward(request, response);
		} catch (DBException e) {
			DBException.lastError = e;
			response.sendRedirect("error");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			UserEntity accountInfo = new UserEntity(request);

			//Check if changing password
			if (request.getParameter("password").length() != 0){
				//Check if old password is OK
				LoginEntity login = new LoginEntity();
				login.login = accountInfo.login;
				login.password = accountInfo.password;
				if (!DBOperations.checkLogin(login)){
					bean = new AccountBean();
					bean.passwordError = "Old password is invalid";
					bean.user = accountInfo;
					response.sendRedirect("account");
					return;
				} else if (request.getParameter("newPassword").length() == 0){
					bean = new AccountBean();
					bean.newPasswordError = "Enter new password";
					bean.user = accountInfo;
					response.sendRedirect("account");
					return;
				} else if (!request.getParameter("newPassword").equals(request.getParameter("confirmNewPassword"))){
					bean = new AccountBean();
					bean.newPasswordError = "New passwords must match";
					bean.user = accountInfo;
					response.sendRedirect("account");
					return;
				}
			} 
			
			//Check if age is OK
			if (accountInfo.ageField.length() > 0 && accountInfo.age == null){
				bean = new AccountBean();
				bean.ageError = "Age must be a valid number";
				bean.user = accountInfo;
				response.sendRedirect("account");
				return;
			}
			
			if (request.getSession() == null || request.getSession().getAttribute("userId") == null){
				throw new DBException(11, "Session seams to be invalid");
			}			
			
			accountInfo.id = (Integer)request.getSession().getAttribute("userId");
			DBOperations.updateUser(accountInfo);
			
			bean = new AccountBean();
			bean.user = accountInfo;
			bean.updateStatus = "Account information updated succesfully";
			if (accountInfo.name != null)
				request.getSession().setAttribute("userName", accountInfo.name);
			else
				request.getSession().setAttribute("userName", accountInfo.login);
			response.sendRedirect("account");
		} catch (DBException e) {
			e.printStackTrace();
			response.sendRedirect("error");
		}
	}

}
